package com.lvhr.rpc.springboot.starter.bootstrap;

import cn.hutool.core.util.StrUtil;
import com.lvhr.rpc.RpcApplication;
import com.lvhr.rpc.config.RpcConfig;
import com.lvhr.rpc.server.tcp.VertxTcpServer;
import com.lvhr.rpc.springboot.starter.annotation.EnableRpc;
import com.lvhr.rpc.utils.ConfigUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Collections;

/**
 * Rpc 框架启动
 *
 */
@Slf4j
public class RpcInitBootstrap implements ImportBeanDefinitionRegistrar {

    /**
     * Spring 初始化时执行，初始化 RPC 框架
     *
     * @param importingClassMetadata
     * @param registry
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 获取 EnableRpc 注解的属性值
        boolean needServer = (boolean) importingClassMetadata.getAnnotationAttributes(EnableRpc.class.getName())
                .get("needServer");

        String needYml = (String) importingClassMetadata.getAnnotationAttributes(EnableRpc.class.getName())
                .get("needYml");
        String environment = (String)importingClassMetadata.getAnnotationAttributes(EnableRpc.class.getName())
                .get("environment");

        // RPC 框架初始化（配置和注册中心）
        if (needYml.equals("yml") && environment.equals("prod") ) {
            RpcConfig rpc = ConfigUtils.loadConfig(RpcConfig.class, "rpc", "prod", Collections.singletonList("yml"));
            RpcApplication.init(rpc);
        }
        else if (StrUtil.isBlank(environment) && needYml.equals("yml")) {
            RpcConfig rpc = ConfigUtils.loadConfig(RpcConfig.class, "rpc", "", Collections.singletonList("yml"));
             RpcApplication.init(rpc);
        }
        else if (needYml.equals("properties") && environment.equals("prod") ){
            RpcConfig rpc = ConfigUtils.loadConfig(RpcConfig.class, "rpc", "prod", Collections.singletonList("properties"));
            RpcApplication.init(rpc);
        }
        else if (needYml.equals("properties") && StrUtil.isBlank(environment) ){
            RpcConfig rpc = ConfigUtils.loadConfig(RpcConfig.class, "rpc", "", Collections.singletonList("properties"));
            RpcApplication.init(rpc);
        }
        else {
            RpcApplication.init();
        }

        // 全局配置
        final RpcConfig rpcConfig = RpcApplication.getRpcConfig();

        // 启动服务器
        if (needServer) {
            VertxTcpServer vertxTcpServer = new VertxTcpServer();
            vertxTcpServer.doStart(rpcConfig.getServer().getPort());
        } else {
            log.info("不启动 server");
        }

    }
}
